package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC495 {
    public long startExecuteTime = System.currentTimeMillis();

    class Solution {
        public int findPoisonedDuration(int[] timeSeries, int duration) {
            int poison = 0;//保存中毒时间
            //判断数组是否为空
            if (timeSeries.length == 0) {
                return 0;
            }
            //当数组长度为1中毒事件就为中毒持续时间
            else if (timeSeries.length == 1) {
                return duration;
            }
            //当数组长度大于1时
            else {
                //将数组的第一个元素保存为中毒开始时间
                int firsttime = timeSeries[0];
                //通过循环算出中毒时间
                for (int i = 0; i < timeSeries.length - 1; i++) {
                    //如果当前中毒开始时间 + 中毒持续时间 < 下一次中毒开始时间则第一轮中毒时间为中毒持续时间（duration）
                    if (firsttime + duration <= timeSeries[i + 1]) {
                        poison += duration;

                    } else {
                        poison += timeSeries[i + 1] - firsttime;

                    }
                    firsttime = timeSeries[i + 1];

                }
            }

            return poison + duration;
        }
    }

    class Solution_Fail_Unknown {
        public int findPoisonedDuration(int[] timeSeries, int duration) {
            if (null == timeSeries || timeSeries.length <= 0) return 0;
            int totalTime = duration, lastHit = timeSeries[0];
            for (int i = 1; i < timeSeries.length; i++) {
                if (lastHit + duration <= timeSeries[i]) totalTime += duration;
                else totalTime += timeSeries[i] - timeSeries[i - 1];
                lastHit = timeSeries[i];
            }

            return totalTime;
        }
    }

    public void run() {
        Solution_Fail_Unknown solution = new Solution_Fail_Unknown();
        int[] arr = InputUtil.readLongArrayFromFile("longArray.txt");
        System.out.println(solution.findPoisonedDuration(arr, 5));
    }

    public static void main(String[] args) throws Exception {
        LC495 an = new LC495();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
